package com.sun.springbootfiledownload.controller;

import com.aliyun.oss.model.OSSObject;
import com.sun.springbootfiledownload.result.AliyunOssResult;
import com.sun.springbootfiledownload.utils.AliyunOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.HttpHeaders;

import java.io.IOException;

/**
 * @version 1.0
 * @Package: com.sun.springbootfiledownload.controller
 * @ClassName: AliyunOSSController
 * @Author: sgq
 * @Date: 2025/4/9 11:19
 * @Description: TODD
 */
@Slf4j
@RestController
@RequestMapping("/api/oss")
public class AliyunOssController {

    @Autowired
    private AliyunOssUtil aliyunOSSUtil;

    /**
     * 上传文件到OSS
     *
     * @param file   上传的文件
     * @param folder 上传到的文件夹
     * @return 文件访问URL
     */
    @PostMapping("/upload")
    public AliyunOssResult uploadToOSS(@RequestParam("file") MultipartFile file,
                                       @RequestParam(value = "folder", defaultValue = "default") String folder) throws IOException {
        return aliyunOSSUtil.upload(file.getInputStream(), folder);
    }

    /**
     * 从OSS下载文件
     *
     * @param filePath OSS中的文件路径
     * @return 文件响应实体
     */
    @GetMapping("/download")
    public ResponseEntity<byte[]> downloadFromOSS(@RequestParam String filePath) throws IOException {
        OSSObject ossObject = aliyunOSSUtil.get(filePath);
        byte[] fileContent = ossObject.getObjectContent().readAllBytes();

        // 从文件路径中提取文件名
        String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", fileName);

        return ResponseEntity.ok()
                .headers(headers)
                .body(fileContent);
    }
}